package com.kaibes.core.base.proxy;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarLoader {

    private String root;

    private JarLoader(String root) {
        this.root = root;
    }
    
    public List<Class<?>> loadJar(String fileName) throws IOException {
        String path = "file:"+root + "/" + fileName;
        URL[] urls = new URL[] { new URL(path) };
        return loadJar(urls);
    }
    
    // 加载JAR
    public List<Class<?>> loadJar(URL[] urls) throws IOException {
        List<Class<?>> clazzList = new ArrayList<>();
        URLClassLoader classLoader = URLClassLoader.newInstance(urls);
        String filePath = URLDecoder.decode(urls[0].getPath(), "UTF-8");
        JarFile file = new JarFile(filePath);
        Enumeration<JarEntry> entrys = file.entries();
        while (entrys.hasMoreElements()) {
            JarEntry jar = entrys.nextElement();
            String entryName = jar.getName();
            if (entryName.endsWith(".class")) {
                entryName = entryName.replaceAll("/", ".");
                entryName = entryName.substring(0, entryName.length()-6);
                try {
                    Class<?> clazz = classLoader.loadClass(entryName);
                    clazzList.add(clazz);
                } catch (ClassNotFoundException e) {
                }
            }
        }
        file.close();
        return clazzList;
    }
    
    public static JarLoader newInstance(String root) {
        return new JarLoader(root);
    }
    
}
